﻿
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;

using FreeSql;
using Kalman;
using Newtonsoft.Json.Linq;
using Kalman.Extensions;

namespace QuDao
{
    /// <summary>
    /// 租户业务对象（处理数据表base_tenant相关的业务逻辑）
    /// </summary>
    public sealed partial class TenantBO : SingletonBase<TenantBO>
    {
        readonly IFreeSql fsql;
        public TenantBO() : base()
        {
            fsql = ServiceLocator.Instance.GetRequiredService<IFreeSql>();
        }
        
        /// <summary>
        /// 获取租户
        /// </summary>
        /// <param name="id">主键ID的值</param>
        /// <returns></returns>
        public T GetItem<T>(int id)
        {
        	if (id <= 0) return default;
            var item = fsql.Select<Tenant>().Where(a => a.TenantID == id).ToOne<T>();
            return item;
        }
        
        public Tenant GetItem(int id)
        {
        	return GetItem<Tenant>(id);
        }
        
        /// <summary>
        /// 获取租户详情
        /// </summary>
        /// <param name="id">租户ID</param>
        /// <returns></returns>
        public TenantDetailsDto GetDetails(int id)
        {
            var dto = GetItem<TenantDetailsDto>(id);
            return dto;
        }

        /// <summary>
        /// 获取租户数据列表
        /// </summary>
        /// <param name="pageIndex">页索引，从1开始</param>
        /// <param name="pageSize">每页记录数，默认10</param>
        /// <returns></returns>
        public List<T> GetList<T>(int pageIndex = 1, int pageSize = 10)
        {
            var list = fsql.Select<Tenant>().Page(pageIndex, pageSize).ToList<T>();
            return list;
        }
        
        /// <summary>
        /// 获取租户数据列表
        /// </summary>
        /// <returns></returns>
        public List<T> GetList<T>(int[] ids)
        {
        	if (ids == null || ids.Length == 0) return new List<T>();
            var list = fsql.Select<Tenant>().Where(a => ids.Contains(a.TenantID)).ToList<T>();
            return list;
        }
        
        /// <summary>
        /// 新增租户
        /// </summary>
        public int Add(TenantAddDto dto)
        {
            if (dto.MADiscount >= dto.MBDiscount) throw new AppException("A级会员折扣必须小于B级会员折扣");
            if (dto.MBDiscount >= dto.MCDiscount) throw new AppException("B级会员折扣必须小于C级会员折扣");
            if (dto.MCDiscount > 1) throw new AppException("C级会员折扣不能大于1");
            if (dto.MADiscount < decimal.Zero) throw new AppException("A级会员折扣不能小于零");
            if (dto.L1Ratio + dto.L2Ratio != 1) throw new AppException("直推加间推值必须等于1");

            var entity = dto.CopyTo<Tenant>();
        	
            entity.CreateTime = DateTime.Now;
            entity.ModifyTime = DateTime.Now;
            return fsql.Insert(entity).ExecuteAffrows();
        }

        /// <summary>
        /// 修改租户
        /// </summary>
        public int Modify(TenantModifyDto dto)
        {
            if (dto.MADiscount >= dto.MBDiscount) throw new AppException("A级会员折扣必须小于B级会员折扣");
            if (dto.MBDiscount >= dto.MCDiscount) throw new AppException("B级会员折扣必须小于C级会员折扣");
            if (dto.MCDiscount > 1) throw new AppException("C级会员折扣不能大于1");
            if (dto.MADiscount < decimal.Zero) throw new AppException("A级会员折扣不能小于零");
            if (dto.L1Ratio + dto.L2Ratio != 1) throw new AppException("直推加间推值必须等于1");

            var item = GetItem<Tenant>(dto.TenantID) ?? throw new AppException($"租户不存在：{dto.TenantID}");

            var update = fsql.Update<Tenant>(dto.TenantID).Set(a => a.ModifyTime, DateTime.Now);
            
            if (dto.TenantName != item.TenantName) update.Set(a => a.TenantName, dto.TenantName);
			if (dto.Linkman != item.Linkman) update.Set(a => a.Linkman, dto.Linkman);
			if (dto.Phone != item.Phone) update.Set(a => a.Phone, dto.Phone);
			if (dto.Address != item.Address) update.Set(a => a.Address, dto.Address);
			if (dto.MADiscount != item.MADiscount) update.Set(a => a.MADiscount, dto.MADiscount);
			if (dto.MBDiscount != item.MBDiscount) update.Set(a => a.MBDiscount, dto.MBDiscount);
			if (dto.MCDiscount != item.MCDiscount) update.Set(a => a.MCDiscount, dto.MCDiscount);
			if (dto.MAName != item.MAName) update.Set(a => a.MAName, dto.MAName);
			if (dto.MBName != item.MBName) update.Set(a => a.MBName, dto.MBName);
			if (dto.MCName != item.MCName) update.Set(a => a.MCName, dto.MCName);
			if (dto.CommissionRatio != item.CommissionRatio) update.Set(a => a.CommissionRatio, dto.CommissionRatio);
			if (dto.CommissionFlag != item.CommissionFlag) update.Set(a => a.CommissionFlag, dto.CommissionFlag);
			if (dto.L1Ratio != item.L1Ratio) update.Set(a => a.L1Ratio, dto.L1Ratio);
			if (dto.L2Ratio != item.L2Ratio) update.Set(a => a.L2Ratio, dto.L2Ratio);
			//if (dto.WxAppID != item.WxAppID && !dto.WxAppID.IsNullOrEmpty()) update.Set(a => a.WxAppID, dto.WxAppID);
			//if (dto.WxAppSecret != item.WxAppSecret && !dto.WxAppSecret.IsNullOrEmpty()) update.Set(a => a.WxAppSecret, dto.WxAppSecret);
			if (dto.ExpressCompanyList != item.ExpressCompanyList) update.Set(a => a.ExpressCompanyList, dto.ExpressCompanyList);
            if (dto.Memo != item.Memo) update.Set(a => a.Memo, dto.Memo);
						
			return update.ExecuteAffrows();
        }

		/// <summary>
        /// 删除租户数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(int[] ids)
        {
        	if (ids == null || ids.Length == 0) return 0;
        	return fsql.Delete<Tenant>().Where(a => ids.Contains(a.TenantID)).ExecuteAffrows();
        }
        
        /// <summary>
        /// 删除租户数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(int id)
        {
        	return fsql.Delete<Tenant>(id).ExecuteAffrows();
        }
        
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="req">分页查询请求对象</param>
        public PagingResult<Tenant> Query(PagingRequest req)
        {
        	if (req == null) throw new AppException("查询数据不能为空");
        	
            var select = fsql.Select<Tenant>();
            foreach (var item in req.FilterItems)
            {
                switch (item.Field)
                {
                    case "TenantID":
                        select.Where(a => a.TenantID == int.Parse(item.Value));
                        break;
                    //case "TenantName":
                    //    select.Where(a => a.TenantName.Contains(item.Value));
                    //    break;
                    default:
                        break;
                }
            }

            if (!string.IsNullOrEmpty(req.SortExp))
            {
                select.OrderBy(req.SortExp);//自定义排序
            }
            else
            {
                select.OrderByDescending(a => a.TenantID);//默认排序
            }

            //var sql = select.ToSql();

            var list = select.Count(out var total).Page(req.PageIndex, req.PageSize).ToList<Tenant>();
            return new PagingResult<Tenant>
            {
                PageIndex = req.PageIndex,
                PageSize = req.PageSize,
                Data = list,
                Total = (int)total
            };
        }
        
    }
}
